<?php
/**
 * Created by PhpStorm.
 * User: 阿沁
 * Date: 2024/3/20
 * Time: 14:11
 * SOURCE: 中国大陆工时规管现况（标准工时）：
 *              一天工作时间为8小时，平均每周工时不超过40小时;
 *              加班上限为一天3小时及一个月36小时，逾时工作薪金不低于平日工资的150％。
 *              而一周最高工时则为48小时。平均每月计薪天数为21.75天。
 * TO: 我是阿沁,健康撸代码,拒绝通宵。
 * 版权所有: © 2024-2030 阿沁
 * WARNING: 未经本人许可, 禁止一切商用
 * CLASS: < Common.php >
 */

namespace app\common;


use DateTime;
use DateTimeZone;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\facade\Cache;
use think\facade\Config;
use Throwable;

class Platform
{

	
	/**
	 * 获取移动应用access_token
	 * @throws Throwable
	 */
	public static function getWechatMobileAccessToken($code)
	{
		return Cache::remember('mobile_access_token',function ()use($code){
			$client = new Client();
			$appid = Config::get('platform.wechat_open.mobile.appid');
			$secret = Config::get('platform.wechat_open.mobile.secret');
			//获取接口调用凭据
			$wechat = $client->post("https://api.weixin.qq.com/sns/oauth2/access_token", [
				'query' => [
					'appid' => $appid,
					'secret' => $secret,
					'code' => $code,
					'grant_type' => 'client_credential',
				]
			]);
			$wechat = json_decode($wechat->getBody()->getContents());
			if (!isset($wechat->unionid)) {
				throw new Exception('移动凭据接口调用失败');
			}
			return $wechat;
		},7000);
	}
	
	
	/**
	 * 获取网页应用access_token
	 * @throws Throwable
	 */
	public static function getWechatWebAccessToken($code)
	{
		return Cache::remember('web_access_token',function ()use($code){
			$client = new Client();
			$appid = Config::get('platform.wechat_open.web.appid');
			$secret = Config::get('platform.wechat_open.web.secret');
			//获取接口调用凭据
			$wechat = $client->post("https://api.weixin.qq.com/sns/oauth2/access_token", [
				'query' => [
					'appid' => $appid,
					'secret' => $secret,
					'code' => $code,
					'grant_type' => 'client_credential',
				]
			]);
			$wechat = json_decode($wechat->getBody()->getContents());
			if (!isset($wechat->unionid)) {
				throw new Exception('网页凭据接口调用失败');
			}
			return $wechat;
		},7000);
	}
	
	/**
	 * 获取微信小程序openid
	 * @param $code
	 * @return mixed
	 * @throws Exception|GuzzleException
	 */
	public static function getWechatMobileOpenid($code)
	{
		$client = new Client();
		$appid = Config::get('platform.wechat_open.mobile.appid');
		$secret = Config::get('platform.wechat_open.mobile.secret');
		$login = $client->get("https://api.weixin.qq.com/sns/oauth2/access_token", [
			'query' => [
				'appid' => $appid,
				'secret' => $secret,
				'code' => $code,
				'grant_type' => 'authorization_code'
			]
		]);
		$wechat = json_decode($login->getBody()->getContents());
		if (!isset($wechat->openid)) {
			throw new \Exception($wechat->errmsg);
		}
		return $wechat->openid;
	}
	
	public static function getWechatOpenid($wechatcode)
	{
		$client = new Client();
		$appid = Config::get('wechat.wechat_mini.appid');
		$secret = Config::get('wechat.wechat_mini.secret');
		$login = $client->get("https://api.weixin.qq.com/sns/oauth2/access_token", [
			'query' => [
				'appid' => $appid,
				'secret' => $secret,
				'code' => $wechatcode,
				'grant_type' => 'authorization_code'
			]
		]);
		$wechat = json_decode($login->getBody()->getContents());
		if (!isset($wechat->openid)) {
			throw new \Exception($wechat->errmsg);
		}
		return $wechat->openid;
	}
	
	/**
	 * 小程序获取接口调用凭据
	 * @return mixed
	 * @throws Throwable
	 */
	public static function getWechatMiniToken()
	{
		return Cache::remember('wechat_mini_access_token',function (){
			$client = new Client();
			$appid = Config::get('platform.wechat.mini.appid');
			$secret = Config::get('platform.wechat.mini.secret');
			//获取接口调用凭据
			$wechat = $client->get("https://api.weixin.qq.com/cgi-bin/token", [
				'query' => [
					'appid' => $appid,
					'secret' => $secret,
					'grant_type' => 'client_credential',
				]
			]);
			$wechat = json_decode($wechat->getBody()->getContents());
			if (!isset($wechat->access_token)) {
				throw new Exception('获取接口调用凭据失败');
			}
			return $wechat->access_token;
		},7000);
	}
	
	/**
	 * 获取小程序openid
	 * @param $code
	 * @return mixed
	 * @throws GuzzleException
	 */
	public static function getWechatMiniOpenid($code)
	{
		$client = new Client();
		$appid = Config::get('platform.wechat.mini.appid');
		$secret = Config::get('platform.wechat.mini.secret');
		$login = $client->get("https://api.weixin.qq.com/sns/jscode2session", [
			'query' => [
				'appid' => $appid,
				'secret' => $secret,
				'js_code' => $code,
				'grant_type' => 'authorization_code'
			]
		]);
		$wechat = json_decode($login->getBody()->getContents());
		if (!isset($wechat->openid)) {
			throw new \Exception($wechat->errmsg);
		}
		return $wechat->openid;
	}

    #小程序发货
    public static function uploadShippingInfo($transaction_id,$item_desc,$openid)
    {
        $client = new Client();
        $access_token = self::getWechatMiniToken();
        $date = new DateTime(date('Y-m-d H:i:s'), new DateTimeZone('Asia/Shanghai'));
        $formatted_date = $date->format('c');
        $ret = $client->post("https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=$access_token", [
            'body' => json_encode([
                'order_key' => ['order_number_type'=>2,'transaction_id'=>$transaction_id],
                'logistics_type' => 4,
                'delivery_mode' => 1,
                'shipping_list' => [[
                    'item_desc'=>$item_desc
                ]],
                'upload_time'=>$formatted_date,
                'payer'=>['openid'=>$openid]
            ])
        ]);
        $ret = json_decode($ret->getBody()->getContents());
        if ($ret->errcode!=0) {
            throw new \Exception($ret->errmsg);
        }
    }
	
}